<?php
/**
 *
 */

class KhachHang extends ModelBase
{
    public function __construct()
    {
        parent::__construct(__CLASS__);
    }

    public function isValidUser($user, $pass = '')
    {
        if (!empty($pass)) {
            $user = array(
                'uid' => $user,
                'pwd' => $pass
            );
        }

        $user['pwd'] = encodePassword($user['pwd']);

        $valid = count($this->select('taikhoankh = :uid AND matkhaukh = :pwd', $user)) > 0;
        if (!$valid) {
            return json_encode(array('code' => '0', 'html' => ''));
        } else {
            $_SESSION[SESSION_KH] = $user['uid'];
            $html = new Template(TEMPLATE_DIR . 'khachhang-msg-logged.html');
            $html['taikhoankh'] = $user['uid'];
            return json_encode(array('code' => '1', 'html' => $html->render()));
        }
    }

    public function exists($id)
    {
        $valid = count($this->select('taikhoankh = :uid', array('uid' => $id)));
        return $valid;
    }

    /**
     * Đăng ký khách hàng mới
     * @param $params
     */
    public function register($params) {
        if (isset($params['hotenkh']) && isset($params['diachikh']) && isset($params['sodtkh'])
            && isset($params['emailkh']) && isset($params['taikhoankh']) && isset($params['matkhaukh'])
            && !$this->exists($params['taikhoankh'])) {
            $params['matkhaukh'] = encodePassword($params['matkhaukh']);
            $this->insert($params);
            return json_encode(array('errcode' => '0', 'errmsg' => ''));
        } else {
            return json_encode(array('errcode' => '1', 'errmsg' => 'Thông tin không hợp lệ'));
        }
    }
    public function logout()
    {
        if ($this->isLogged()) {
            unset($_SESSION[SESSION_KH]);
        }

        $html = new Template(TEMPLATE_DIR . 'khachhang-msg.html');
        return $html->render();
    }

    public function isLogged()
    {
        return isset($_SESSION[SESSION_KH]) ? '1' : '0';
    }

    public function requestCurrentAddress()
    {
        if ($this->isLogged()) {
            $kh = $this->select('taikhoankh=:id', array('id' => $_SESSION[SESSION_KH]));

            return json_encode(array('errcode' => '0', 'address' => $kh[0]['diachikh']));
        } else {
            return json_encode(array('errcode' => 1));
        }
    }

    public static function getMakh($taikhoan)
    {
        $link = new KhachHang();
        $makh = $link->executeScalar('SELECT makh FROM khachhang WHERE taikhoankh=:tk', array('tk' => $taikhoan));
        $link->disconnect();
        if ($makh == null) {
            return '$';
        } else {
            return $makh;
        }
    }

}
